package com.ghp.admin.controller;

import com.ghp.common.utils.response.ResponseResult;
import com.ghp.request.annotation.RequestLimit;
import com.ghp.request.enums.RequestLimitStrategy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;

import static com.ghp.common.constants.ErrorMessageConstants.PARAMS_NOT_NULL;
import static com.ghp.common.constants.MessageQueueConstants.EXCHANGE_CAPTCHA;
import static com.ghp.common.constants.MessageQueueConstants.ROUTING_KEY_CAPTCHA;
import static com.ghp.common.constants.RedisConstants.LOGIN_CAPTCHA_KEY;
import static com.ghp.common.constants.RegexConstants.EMAIL_REGEX;
import static com.ghp.common.constants.RegexConstants.PHONE_REGEX;

/**
 * @author ghp
 * @title
 * @description
 */
@RestController
@RequestMapping("/sms")
@Validated
public class SmsController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    @RequestLimit(strategy = RequestLimitStrategy.TOKEN_BUCKET, qps = 1)
    public ResponseResult SendCaptcha(@Pattern(regexp = PHONE_REGEX + "|" + EMAIL_REGEX,
            message = "手机号或邮箱格式错误")
                                      @NotBlank(message = PARAMS_NOT_NULL)
                                      String phoneOrEmail) {
        String captcha = (String) redisTemplate.opsForValue().get(LOGIN_CAPTCHA_KEY + phoneOrEmail);
        if (StringUtils.isNotBlank(captcha)) {
            return ResponseResult.fail("验证码还在有效期内，请勿重复发送");
        }
        // 往队列中添加一个任务，异步更新发送短信
        rabbitTemplate.convertAndSend(EXCHANGE_CAPTCHA, ROUTING_KEY_CAPTCHA, phoneOrEmail);
        return ResponseResult.success();
    }

}
